package jsen.tool.ddd.demo.domain.brand.spec;

import jsen.tool.ddd.adapter.infrastructure.specification.base.CompositeSpecification;
import jsen.tool.ddd.adapter.infrastructure.specification.base.SpecContext;
import jsen.tool.ddd.demo.domain.brand.Brand;
import org.apache.commons.lang3.StringUtils;

import java.util.Set;

/**
 * 品牌名字一致性含义：
 * 品牌名字不能为空 & 不能重复
 *
 * @author jsen
 * @date 2021/10/6
 */
public class BrandNameSpec extends CompositeSpecification<Brand> {
    private final Set<String> existBrandNameSet;

    public BrandNameSpec(Set<String> existBrandNameSet) {
        this.existBrandNameSet = existBrandNameSet;
    }

    @Override
    public boolean isSatisfiedBy(SpecContext<Brand> t) {
        Brand brand = t.getData();
        if (StringUtils.isBlank(brand.getName())) {
            t.addError("BrandNameSpec", "品牌名字不能为空");
            return false;
        }

        if (isBrandNameExisted(brand.getName())) {
            t.addError("BrandNameSpec", "品牌名字不能重复");
            return false;
        }
        return true;
    }

    private boolean isBrandNameExisted(String name) {
        return existBrandNameSet.contains(name);
    }


}
